package com.hmdp.service.impl;

import cn.hutool.core.util.IdUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.UserHolder;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;


    /**
     * 优惠券秒杀下单
     *
     * @param voucherId
     * @return
     */
    @Override
    @Transactional
    public Result seckillVoucher(Long voucherId) {
        // 根据优惠券id查询优惠券开始时间和结束时间
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
        LocalDateTime beginTime = seckillVoucher.getBeginTime();
        LocalDateTime endTime = seckillVoucher.getEndTime();
        // 如果还没到开始时间或者已经到结束时间，无法下单，抛出异常
        if (LocalDateTime.now().isBefore(beginTime)) {
            return Result.fail("秒杀还没开始");
        }
        if (LocalDateTime.now().isAfter(endTime)) {
            return Result.fail("秒杀已经结束");
        }
        // 查询优惠券库存
        Integer stock = seckillVoucher.getStock();
        // 如果库存不足，无法下单，抛出异常
        if (stock < 1) {
            return Result.fail("库存不足");
        }

        Long userId = UserHolder.getUser().getId();
        synchronized (userId.toString().intern()) {
            IVoucherOrderService currentProxy = (IVoucherOrderService) AopContext.currentProxy();
            return currentProxy.createVoucherOrder(voucherId);
        }
    }

    public Result createVoucherOrder(Long voucherId) {
        // 一人一单
        Long userId = UserHolder.getUser().getId();
        // 根据用户id和优惠券id查询订单
        int count = this.query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        // 判断是否存在
        if (count > 0) {
            // 存在表示用户购买过
            return Result.fail("用户已经购买过一次");
        }
        // 库存充足，扣除库存
        boolean updateIsSuccess = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherId).gt("stock", 0).update(); // where voucher_id = ? and stock > 0
        if (!updateIsSuccess) {
            return Result.fail("库存不足");
        }
        // 创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        // 订单id
        long orderId = IdUtil.getSnowflake().nextId();
        voucherOrder.setId(orderId);
        // 用户id
        voucherOrder.setUserId(userId);
        // 优惠券id
        voucherOrder.setVoucherId(voucherId);
        // 生成订单
        this.save(voucherOrder);
        // 返回订单id
        return Result.ok(orderId);
    }
}
